package com.ukao.cashregister.ui.setting;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.WifiTableAdapter;
import com.ukao.cashregister.base.BaseFragment;
import com.ukao.cashregister.bean.ComparatorComment;
import com.ukao.cashregister.dialog.WifiPassDialogFragment;
import com.ukao.cashregister.dialog.WifiStrongDialogFragment;
import com.ukao.cashregister.eventbus.WifiEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.ThreadUtils;
import com.ukao.cashregister.utils.WifiAdminUtils;
import com.ukao.cashregister.widget.SwitchButton;


import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.R.id.message;
import static com.ukao.cashregister.R.id.img_wifi_level_ico;
import static com.ukao.cashregister.R.id.link_wif_layout;
import static com.ukao.cashregister.R.id.txt_wifi_name;


/**
 * 无线网列表
 */
public class WifiListFragment extends BaseFragment {


    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.switch_btn)
    SwitchButton switchBtn;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.wifi_recycler_view)
    LinearLayout wifiRecyclerView;
    Unbinder unbinder;
    @BindView(R.id.line)
    View line;
    @BindView(link_wif_layout)
    RelativeLayout linkWifLayout;
    @BindView(R.id.load_wife_txt)
    TextView loadWifeTxt;
    @BindView(R.id.switch_layout)
    LinearLayout switchLayout;
    @BindView(txt_wifi_name)
    TextView txtWifiName;
    @BindView(img_wifi_level_ico)
    ImageView imgWifiLevelIco;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private WifiAdminUtils mWifiAdmin;
    private List<ScanResult> mlist;
    private WifiTableAdapter mWifiTableAdapter;
    private WifiReceiver mReceiver;
    private boolean loadSucceed;
    private   ScanResult scanResult;



    public static WifiListFragment newInstance(String param1, String param2) {
        WifiListFragment fragment = new WifiListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_wifi_list, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {

        loadSucceed = false;
        mlist = new ArrayList<ScanResult>();
        initLinearRecyclerView(recyclerView);
        mWifiTableAdapter = new WifiTableAdapter(_mActivity, mlist,false);
        recyclerView.setAdapter(mWifiTableAdapter);
        mWifiAdmin = new WifiAdminUtils(_mActivity);


    }

    @Override
    protected void initListener() {
        super.initListener();
        mWifiTableAdapter.setOnItemClickListener(mOnItemClickListener);
    }

    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            ScanResult scanResult =(ScanResult)o;
            isConnect(scanResult);


        }
    };

    /**
     * 连接wifi对话框

     */private void isConnect(final ScanResult scanResult  ) {
        if (mWifiAdmin.isConnect(scanResult)) {
            // 已连接，显示连接状态对话框
            WifiStrongDialogFragment mWifiStrongDialogFragment=new WifiStrongDialogFragment();
            Bundle mBundle=new Bundle();
            mBundle.putParcelable(ARG_PARAM1,scanResult);
            mWifiStrongDialogFragment.setArguments(mBundle);
            mWifiStrongDialogFragment.show(getChildFragmentManager(),mWifiStrongDialogFragment.getClass().getName());

        } else {

            if ( ! mWifiAdmin.checkIsCurrentWifiHasPassword(scanResult.capabilities)){
                ThreadUtils.runOnBackgroundThread(new Runnable() {
                    @Override
                    public void run() {
                        boolean iswifi =mWifiAdmin.addNetwork(mWifiAdmin.createWifiInfo(scanResult.SSID,"",0));//连接wifi

                    }
                });


            }else{
                // 未连接显示连接输入对话框
                WifiPassDialogFragment mWifiPassDialogFragment=new WifiPassDialogFragment();
                Bundle mBundle=new Bundle();
                mBundle.putParcelable(ARG_PARAM1,scanResult);
                mWifiPassDialogFragment.setArguments(mBundle);
                mWifiPassDialogFragment.setOnSureClickListener(mOnDialogSureClickListener);
                mWifiPassDialogFragment.show(getChildFragmentManager(),mWifiPassDialogFragment.getClass().getName());
            }



        }
    }

    private   OnDialogSureClickListener  mOnDialogSureClickListener=new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            Map mMap = (Map) message;
            final      String    txtWifiNames= (String) mMap.get(ARG_PARAM1);
            final   String    wifiPass= (String) mMap.get(ARG_PARAM2);
            final   int    type= (int) mMap.get(ARG_PARAM3);
            ThreadUtils.runOnBackgroundThread(new Runnable() {
                @Override
                public void run() {
                    L.i("txtWifiNames="+txtWifiNames+"wifiPass="+wifiPass);
                    mWifiAdmin.addNetwork(mWifiAdmin.createWifiInfo(txtWifiNames,wifiPass,type));//连接wifi

                }
            });

        }
    };




    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        registerReceiver();
        if (mWifiAdmin.getWifiManager().isWifiEnabled()) {
            linkWifLayout.setVisibility(View.GONE);
            openWifi();


        } else {
            closeWifi();

        }


    }





    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();

        if (!CheckUtils.isNull(mReceiver)) {
            _mActivity.unregisterReceiver(mReceiver);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(WifiEvent event) {
        switch (event.getMessage()) {
            case  link:/*链接wifi*/




                break;
            case  notSave:

                mWifiAdmin.disConnectionWifi(mWifiAdmin.getConnNetId());

                break;
        }
    }



    @OnClick({R.id.switch_layout, link_wif_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.switch_layout:
                if (switchBtn.isSwitchOpen()) {
                    closeWifi();
                } else {
                    openWifi();
                }
                break;
            case link_wif_layout:

                if (!CheckUtils.isNull(scanResult)){
                    isConnect(scanResult);


                }

                break;

        }
    }

    private void closeWifi() {
        loadWifeTxt.setVisibility(View.INVISIBLE);
        switchBtn.closeSwitch();
        line.setVisibility(View.GONE);
        linkWifLayout.setVisibility(View.GONE);
        mWifiAdmin.getWifiManager().setWifiEnabled(false);
        recyclerView.setVisibility(View.GONE);



    }

    private void openWifi() {
        switchBtn.openSwitch();
        line.setVisibility(View.VISIBLE);
        mWifiAdmin.startScan();

    }






    private void registerReceiver() {
        mReceiver = new WifiReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        _mActivity.registerReceiver(mReceiver, filter);
    }


    private void  showConnect( ScanResult scanResult ){

        linkWifLayout.setVisibility(View.VISIBLE);
        txtWifiName.setText(scanResult.SSID);
        int level = scanResult.level;
        int imgId = R.mipmap.wifi_4;


        if (!mWifiAdmin.checkIsCurrentWifiHasPassword(scanResult.capabilities)) {
            if (Math.abs(level) > 100) {
                imgId = R.mipmap.wifi_none_3;
            } else if (Math.abs(level) > 80) {
                imgId = R.mipmap.wifi_none_3;
            } else if (Math.abs(level) > 70) {
                imgId = R.mipmap.wifi_none_3;
            } else if (Math.abs(level) > 60) {
                imgId = R.mipmap.wifi_none_2;
            } else if (Math.abs(level) > 50) {
                imgId = R.mipmap.wifi_none_2;
            } else {
                imgId = R.mipmap.wifi_none_1;
            }
        } else {

            if (Math.abs(level) > 100) {
                imgId = R.mipmap.wifi_3;
            } else if (Math.abs(level) > 80) {
                imgId = R.mipmap.wifi_3;
            } else if (Math.abs(level) > 70) {
                imgId = R.mipmap.wifi_3;
            } else if (Math.abs(level) > 60) {
                imgId = R.mipmap.wifi_2;
            } else if (Math.abs(level) > 50) {
                imgId = R.mipmap.wifi_2;
            } else {
                imgId = R.mipmap.wifi_1;
            }
        }

        imgWifiLevelIco.setImageResource(imgId);
    }


    private void setWifiData(List<ScanResult> tmpList) {

        if (CheckUtils.isEmpty(tmpList)) {

            mWifiTableAdapter.getDatas().clear();
            mWifiTableAdapter.notifyDataSetChanged();
        } else {
            setConnect(tmpList);

        }


    }

    private      void     setConnect(List<ScanResult> tmpList) {

        if (mWifiAdmin.isConnect(tmpList.get(0))) {
            this.scanResult=tmpList.get(0);
            showConnect(scanResult);
        }

        recyclerView.setVisibility(View.VISIBLE);
       // Collections.sort(tmpList,new ComparatorComment());
        mWifiTableAdapter.setDatas(tmpList);

    }


    private class WifiReceiver extends BroadcastReceiver {
        protected static final String TAG = "ukao";


        @Override
        public void onReceive(Context context, Intent intent) {

            List<ScanResult> wifiList = mWifiAdmin.getWifiManager().getScanResults();
            setWifiData(wifiList);
            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {// wifi连接上与否
                Log.d(TAG, "网络已经改变");

                NetworkInfo info = intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    Log.d(TAG, "wifi已经断开");
                    showNullWifi();

                } else if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
                    Log.d(TAG, "正在连接...");

                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    WifiManager wifiManager = (WifiManager) context
                            .getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    Log.d(TAG, "连接到网络：" + wifiInfo.getBSSID());
                    txtWifiName.setText(wifiInfo.getSSID());
                    linkWifLayout.setVisibility(View.VISIBLE);

                }

            } else if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR,
                        0);

                switch (error) {

                    case WifiManager.ERROR_AUTHENTICATING:
                        T.show("密码错误");
                        Log.d(TAG, "密码认证错误Code为：" + error);

                        break;

                    default:
                        break;
                }

            } else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                ;
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                Log.e("ukao", "wifiState" + wifiState);


                switch (wifiState) {

                    case WifiManager.WIFI_STATE_DISABLING:/*Wifi关闭*/
                        switchBtn.closeSwitch();
                        setEnbledSwitchButton(false, 0.2f);
                        break;
                    case WifiManager.WIFI_STATE_DISABLED:/*Wifi关闭完*/

                        setEnbledSwitchButton(true, 1f);
                        break;
                    case WifiManager.WIFI_STATE_ENABLING:/*Wifi打开*/
                        switchBtn.openSwitch();
                        setEnbledSwitchButton(false, 0.2f);
                        loadWifiDialog(View.VISIBLE);
                        break;
                    case WifiManager.WIFI_STATE_ENABLED:/*Wifi完*/

                        setEnbledSwitchButton(true, 1f);
                        loadWifiDialog(View.INVISIBLE);

                        break;

                }
            }
        }

    }

    private void showNullWifi() {
        txtWifiName.setText("");
        linkWifLayout.setVisibility(View.GONE);
        scanResult=null;
    }


    /**
     * 开启时设置
     * @param enabled
     * @param alpha
     */
    private void setEnbledSwitchButton(boolean enabled, float alpha) {
        switchLayout.setEnabled(enabled);
        switchLayout.setAlpha(alpha);
    }

    private void loadWifiDialog(int visible) {
        loadWifeTxt.setVisibility(visible);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }


}
